import React from "react";
import { connect } from "react-redux";
import { browserHistory } from "react-router";
import fetch from "../../utils/fetch";
import { logIn, recieveUser } from "../../actions/actions";
import { Input, Button, Icon, Form, Row } from "antd";
import './index.scss';
// import crypto from "crypto";

// const generatePasswd = passwd =>
//   crypto
//     .createHash("md5")
//     .update(passwd)
//     .digest("hex");
const FormItem = Form.Item;

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    const { tel } = this.props.user;
    if (tel) {
      browserHistory.push("/");
    }
  }
  handleClick = () => {
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }
      fetch("/api/adminlog", { ...values }).then((data) => {
        const { token, user } = data;
        const { tel } = user;
        dispatch(logIn({ tel }));
        localStorage.setItem("token", token);
        dispatch(recieveUser(user));
        browserHistory.push("/");
      });
    });
  }
  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <div className="login-form">
        <div className="logo">
          <img alt={"logo"} />
          <span>来人呐</span>
        </div>
        <form>
          <FormItem>
            {getFieldDecorator("tel", {
              rules: [
                {
                  required: true,
                  message: '该字段必填'
                }
              ]
            })(
              <Input
                onPressEnter={this.handleClick}
                placeholder="请输入电话号码"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator("passwd", {
              rules: [
                {
                  required: true,
                  message: '该字段必填'
                }
              ]
            })(
              <Input
                type="password"
                onPressEnter={this.handleClick}
                placeholder="请输入密码"
              />
            )}
          </FormItem>
          <Row>
            <Button type="primary" size="small" onClick={this.handleClick}>
              登陆
            </Button>
          </Row>
        </form>
      </div>
    );
  }
}
function mapStateToProps(state) {
  const { user } = state;
  return {
    user
  };
}

export default connect(mapStateToProps)(Form.create()(Login));
